package handlers

import (
	"219yk/api/requset"
	"219yk/api/response"
	"219yk/dao"
	"219yk/inits"
	"219yk/models"
	"context"
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"math/rand"
	"strconv"
	"time"
)

func SmsSend(c *gin.Context) {
	var data requset.SmsSend
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	code := rand.Intn(9000) + 1000

	val := inits.Rdb.Set(context.Background(), "sms"+data.Phone, code, time.Minute*5).Val()
	response.ResponseSuccess(c, val)
}

func Login(c *gin.Context) {
	var data requset.Login
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	get := inits.Rdb.Get(context.Background(), "smsCrack"+data.Phone).Val()
	atoi, _ := strconv.Atoi(get)

	if atoi >= 5 {
		response.ResponseError(c, "验证码错误五次,冻结10分钟")
		return
	}

	val := inits.Rdb.Get(context.Background(), "sms"+data.Phone).Val()
	if val != data.Code {
		inits.Rdb.Expire(context.Background(), "smsCrack"+data.Phone, time.Minute*10)
		inits.Rdb.Incr(context.Background(), "smsCrack"+data.Phone)
		response.ResponseError(c, "验证码错误")
		return
	}
	user, err := dao.GetUser(data.Phone)
	if err != nil {
		response.ResponseError(c, "查询失败")
		return
	}
	if user.Phone == "" {
		m := models.User{
			Phone: data.Phone,
		}
		err := dao.Create(m)
		if err != nil {
			response.ResponseError(c, "注册失败")
			return
		}
	}
	claims := jwt.CustomClaims{ID: user.ID}
	token, err := jwt.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "token生成错误")
		return
	}
	response.ResponseSuccess(c, token)
}
